import {defineStore} from "pinia";
import {ref} from "vue";
import {
    getProblemCodeApi,
    type ProblemCodeForm, removeProblemCodeApi,
    saveProblemCodeApi,
    updateProblemCodeApi
} from "@/api/server/problem-code.ts";

export const useProblemCodeStore = defineStore('problemCode', () => {
    const problemId = ref('')
    const language = ref(1)
    const mainFunction = ref('')
    const userFunction = ref('')

    async function saveProblemCodeService(problemCodeForm: ProblemCodeForm) {
        await saveProblemCodeApi(problemCodeForm)
        problemId.value = problemCodeForm.problemId
        language.value = problemCodeForm.language
        mainFunction.value = problemCodeForm.mainFunction
        userFunction.value = problemCodeForm.userFunction
    }

    async function updateProblemCodeService(problemCodeForm: ProblemCodeForm) {
        await updateProblemCodeApi(problemCodeForm)
        problemId.value = problemCodeForm.problemId
        language.value = problemCodeForm.language
        mainFunction.value = problemCodeForm.mainFunction
        userFunction.value = problemCodeForm.userFunction
    }

    async function initProblemCodeService(newProblemId: string, newLanguage: number) {
        const problemCode = await getProblemCodeApi(newProblemId, newLanguage) as any
        problemId.value = problemCode.problemId
        language.value = problemCode.language
        mainFunction.value = problemCode.mainFunction
        userFunction.value = problemCode.userFunction
    }

    async function removeProblemCodeService(newProblemId: string, newLanguage: number) {
        await removeProblemCodeApi(newProblemId, newLanguage)
        problemId.value = ''
        language.value = 1
        mainFunction.value = ''
        userFunction.value = ''
    }

    return {
        problemId,
        language,
        mainFunction,
        userFunction,
        saveProblemCodeService,
        updateProblemCodeService,
        initProblemCodeService,
        removeProblemCodeService
    }
})